import router from "@/router";
import storage from "store";
import { getItem, setItem } from "@/utils/localStorage";
import { PLAYNEWPAGENAME } from "@/utils/constant";

export const copyText = (text) => {
  // 数字没有 .length 不能执行selectText 需要转化成字符串
  const textString = text.toString();
  let input = document.querySelector("#copy-input");
  if (!input) {
    input = document.createElement("input");
    input.id = "copy-input";
    input.readOnly = "readOnly"; // 防止ios聚焦触发键盘事件
    input.style.position = "absolute";
    input.style.left = "-1000px";
    input.style.zIndex = "-1000";
    document.body.appendChild(input);
  }
  input.value = textString;
  // ios必须先选中文字且不支持 input.select();
  selectText(input, 0, textString.length);
  if (document.execCommand("copy")) {
    document.execCommand("copy");
  }
  input.blur();

  // input自带的select()方法在苹果端无法进行选择，所以需要自己去写一个类似的方法
  // 选择文本。createTextRange(setSelectionRange)是input方法
  function selectText(textbox, startIndex, stopIndex) {
    if (textbox.createTextRange) {
      //ie
      const range = textbox.createTextRange();
      range.collapse(true);
      range.moveStart("character", startIndex); //起始光标
      range.moveEnd("character", stopIndex - startIndex); //结束光标
      range.select(); //不兼容苹果
    } else {
      //firefox/chrome
      textbox.setSelectionRange(startIndex, stopIndex);
      textbox.focus();
    }
  }
};
export function uuid() {
  const s = [];
  const hexDigits = "0123456789abcdef";
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  const uuid = s.join("");
  return uuid;
}

export function rodom() {
  // abcdefghijklmnopqrstuvwxyz
  const str = "1234567890";
  const arr = str.split("");
  let result = "";
  for (let i = 0; i < 4; i++) {
    const n = Math.floor(Math.random() * arr.length);
    result += arr[n];
  }
  return result;
}

export function alert(option) {
  // const vm = new Vue({
  //   vuetify,
  //   render: (h) => h(Alert, { props: option, ref: "alert" }),
  // });
  // const instance = vm.$mount();
  // vm.$refs.alert.show();
  // Object.assign(instance, option);
  // document.getElementById("app").appendChild(instance.$el);
  // setTimeout(() => {
  //   vm.$refs.alert.hide();
  //   if (instance.$el) instance.$el.remove();
  // }, 3000);
}

["success", "info", "error"].forEach((type) => {
  // alert[type] = (options) => {
  //   if (typeof options === "string") {
  //     options = {
  //       msg: options,
  //     };
  //   }
  //   options.type = type;
  //   return alert(options);
  // };
});

export function checkDomain(domain) {
  const currentDomain = window.location.hostname;
  if (domain === currentDomain) {
    console.log("The domain matches the current website.");
    return true;
  }
  console.log("The domain does not match the current website.");
  return false;
}

export function encodePath(path) {
  // 使用encodeURI对路径进行编码
  path = encodeURI(path);
  // 替换空格为%20
  path = path.replace(/\s/g, "%20");
  // 替换#为%23
  path = path.replace(/#/g, "%23");
  // 替换?为%3F
  path = path.replace(/\?/g, "%3F");
  return path;
}

/**
 * 节流函数
 */
export function throttle(callback, daly) {
  let timeId = null;
  return function () {
    if (!timeId) {
      timeId = setTimeout(() => {
        callback.call(this, ...arguments);
        timeId = null;
      }, daly);
    }
  };
}
export const debound = (callback, ms) => {
  let timerId = null;
  return function (...args) {
    if (timerId) {
      clearTimeout(timerId);
    }
    timerId = setTimeout(() => {
      callback.call(this, args);
      timerId = null;
    }, ms);
  };
};

export function getKeepAliveInclude(routes) {
  const keepAlivesName = [];
  for (let i = 0; i < routes.length; i++) {
    const route = routes[i];
    if (route.children) {
      const childrenNames = getKeepAliveInclude(route.children);
      keepAlivesName.push(...childrenNames);
    } else if (route.meta.keepAlive) {
      keepAlivesName.push(route.name);
    }
  }

  return keepAlivesName;
}

export const ISDESCENDINGORDER = "isDescendingOrder";

/**
 * 获取是否为降序
 */
export function getIsDescendingOrder() {
  const res = storage.get(ISDESCENDINGORDER);
  if (res === null) {
    return true;
  }
  return res === "1";
}
/**
 * 设置是否为降序
 */
export function setIsDescendingOrder(isDesc) {
  storage.set(ISDESCENDINGORDER, isDesc ? "1" : "0");
}

/**
 * 排序诗歌列表
 * @param {boolean} isDescendingOrder 是否降序
 */

export function sortSgbList(isDescendingOrder) {
  const listJson = getItem();
  if (!listJson) {
    return;
  }
  const list = JSON.parse(listJson);
  list.sort((a, b) => (!isDescendingOrder ? a.xuhao - b.xuhao : b.xuhao - a.xuhao));
  setItem(list);
}

// 将秒数转化为时分秒
export function formatSeconds(value) {
  let theTime = parseInt(value); // 秒
  let theTime1 = 0; // 分
  let theTime2 = 0; // 小时
  if (theTime > 60) {
    theTime1 = parseInt(theTime / 60);
    theTime = parseInt(theTime % 60);
    if (theTime1 > 60) {
      theTime2 = parseInt(theTime1 / 60);
      theTime1 = parseInt(theTime1 % 60);
    }
  }
  let result = `${parseInt(theTime)}`;
  if (result < 10) {
    result = `0${result}`;
  }
  if (theTime1 > 0) {
    result = `${parseInt(theTime1)}:${result}`;
    if (theTime1 < 10) {
      result = `0${result}`;
    }
  } else {
    result = `00:${result}`;
  }
  if (theTime2 > 0) {
    result = `${parseInt(theTime2)}:${result}`;
    if (theTime2 < 10) {
      result = `0${result}`;
    }
  } else {
    result = `00:${result}`;
  }
  return result;
}
export function toPlayPage(
  item,
  type = "shiji",
  routerType = "push",
  query = { from: router.currentRoute.value.fullPath }
) {
  router[routerType]({
    name: PLAYNEWPAGENAME,
    params: {
      id: item._id,
      gedanid: item.shijiIndex,
      type: type,
    },
    query: query,
  });
}

export function isAndroid() {
  return /Android/i.test(navigator.userAgent);
}
window.Qmsg?.config({
  zIndex: 999999999,
});
export const $toast = window.Qmsg;

export const isProd = process.env.__APP_ENV__ === "prod" || process.env.__APP_ENV__ === "pre";

export const hostname = location.hostname;

export const replaceHttpsHostname = () => {
  const protocol = location.protocol;
  const isHttp = protocol === "http:";
  const isLocalhost = ["localhost", "127.0.0.1"].includes(hostname);
  if (isHttp && isProd && !isLocalhost) {
    location.href = "https:" + location.href.replace(protocol, "");
  }
};

/**
 *  {
 *    key:string,
 *    time:number,
 *    firstTime:number,
 *    resultPromises: {resolve,rjeect}[],
 *    result?:Any
 *   }[]
 */

const chachePromise = [];

function pushChachePromise(key, time) {
  const chaCheItem = chachePromise.find((item) => item.key === key);
  if (chaCheItem) {
    chaCheItem.firstTime = Date.now();
    const newPromise = new Promise((resolve, reject) => {
      chaCheItem.resultPromises = [{ resolve, reject }];
    });
    return newPromise;
  }

  const newPromse = new Promise((resolve, reject) => {
    chachePromise.push({
      key,
      time,
      firstTime: Date.now(),
      resultPromises: [{ resolve, reject }],
    });
  });

  return newPromse;
}

/**
 * 缓存请求
 * @param {*} request
 * @param {*} param1
 * @returns
 */
export async function chaCheRequest(request, { time, key } = { time: 500 }) {
  // 释放缓存的结果
  function handleResultPromise(res, type = "resolve") {
    const resultPromises = chachePromise.find((item) => item.key === key)?.resultPromises;

    if (resultPromises) {
      resultPromises.forEach((pro) => {
        pro[type](res);
      });
      chachePromise.find((item) => item.key === key).result = res;
    }
  }

  const keys = chachePromise.map((item) => item.key);
  if (keys.includes(key)) {
    const firstTime = Date.now();
    const chaCheItem = chachePromise.find((item) => item.key === key);
    // 判断时间，如果超过设定的值就会重新更新值
    if (firstTime - chaCheItem.firstTime > chaCheItem.time) {
      request()
        .then(handleResultPromise)
        .catch((error) => handleResultPromise(error, "reject"));
      return pushChachePromise(key, time);
    } else {
      // 如果还在时间范围内，且已经有了结果，则返回结果
      if (chaCheItem.result) {
        return chaCheItem.result;
        // 如果Promise还没有完成，就创建一个新的Promise推入到队列中。
      } else {
        const newPromise = new Promise((resolve, reject) => chaCheItem.resultPromises.push({ resolve, reject }));
        return newPromise;
      }
    }
  } else {
    request()
      .then(handleResultPromise)
      .catch((error) => handleResultPromise(error, "reject"));

    return pushChachePromise(key, time);
  }
}

/**
 * Flutter方法集成
 */
export const Flutter = {
  isFlutter() {
    return window?.Flutter != null;
  },
  /**
   * 后退
   * @returns
   */
  back() {
    console.log("Flutter.isFlutter()", Flutter.isFlutter());
    if (Flutter.isFlutter()) {
      window.Flutter.postMessage("back");
      return true;
    }
    return false;
  },
};
